package leetcode;

/**
 * @Author: Liu Yue
 * @Descripition: 外观算法
 * 「外观数列」是一个整数序列，从数字 1 开始，序列中的每一项都是对前一项的描述。前五项如下：
 *
 * 1.     1
 * 2.     11
 * 3.     21
 * 4.     1211
 * 5.     111221
 * @Date; Create in 2020/2/20 13:26
 **/
public class CountAndSay {

    //参考方法
    static String countAndSay(int n){
        String s = "1";
        while(n>1){
            s += "#";
            String tmp = "";
            int count = 1;
            for(int i=0;i<s.length()-1;i++){
                if(s.charAt(i)==s.charAt(i+1)){
                    count++;
                }else{
                    tmp = tmp+count+s.charAt(i);
                    count = 1;
                }
            }
            s = tmp;
            n--;
        }
        return s;
    }
    //自己算法
    static String countAndSay2(int n){
        String s = "1";
        while( n > 0 ){
            s += "#";
            String tmp = "";
            int count = 1;
            char[] chars = s.toCharArray();
            for(int i=0;i<chars.length-1;i++){
                if(chars[i]==chars[i+1]){
                    count++;
                }else{
                    tmp = tmp + count + chars[i];
                    count = 1;
                }
            }
            s = tmp;
            n--;
        }
        return s;
    }
    static String countAndSay3(int n) {
        if (n == 1) {
            return "1";
        }
        return countAndSayLine(countAndSay3(n - 1));
    }
    //高手解题
    static String countAndSayLine(String line) {
        StringBuilder newLine = new StringBuilder();
        int i = 0;
        int count = 0;
        while (i < line.length()) {
            if (i == 0 || line.charAt(i) == line.charAt(i - 1)) {
                count ++;
            } else {
                newLine.append(count).append(line.charAt(i - 1));
                count = 1;
            }
            if (i == line.length() - 1) {
                newLine.append(count).append(line.charAt(i));
            }
            i++;
        }
        return newLine.toString();
    }
    public static void main(String[] args) {
        //System.out.println(CountAndSay.countAndSay(7));
        System.out.println(CountAndSay.countAndSay3(5));
    }
}
